/*
-------------------------------------------------------------------------------------------------------------
JS Class 
Names:
    zsi.Common:
       0. zsi.ready() state
       1. LoadingBar
       2. CheckObjectResponse 
       3. CoverPage
       4. Form
            1. Submit
            2. Fill   
            3. ClearFields
            4. RequiredFields   
       5. Window
            1. OpenPopUp 
            2. PopUpModel 
       6. Cookie
            1. Read
            2. Create
       7. LoginForm
            1. Init
            2. OnSignIn
       8. Convert
            1.ToBoolean
       9. Icons
            1. Show
      10. NewGuid
      11. CreateListSession
Description: 
This will display progress status.
Developer : Date Modified :  Reason
GMF   : 06/09/2011    :  added ToBoolean
GMF   : 06/07/2011    :  added RequiredFields 
GMF   : 06/02/2011    :  added BaseFunction on Form.Submit
GMF   : 08/27/2010    :  fixed PopUpModel -- set Properties functionality
GMF   : 08/26/2010    :  added public Icons
GMF   : 08/24/2010    :  fixed Form.Submit - unlocked and locked disabled objects when before submit. 
GMF   : 08/20/2010    :  fixed the parameters on Form.Submit function. 
GMF   : 08/13/2010    :  added PopUpModel a DIV pop up window.
GMF   : 07/30/2010    :  added create cookie function 
GMF   : 07/28/2010    :  modified LogInForm view   
GMF   : 07/27/2010    :  added LogInForm Namespace, added init and OnSignIn function   
GMF   : 07/26/2010    :  added Cookie Namespace, added Read function 
GMF   : 07/16/2010    :  added Form Namespace, added Fill function, ClearFields,and merge SubmitFormJSON SubmitFormJSON.
GMF   : 07/14/2010    :  added function CheckObjectResponse
GMF   : 07/08/2010    :  added functionality : made the progress bar should be placed under div.PageTitle.    
GMF   : 06/21/2010    :  Started 


 ----------------------------------------------------------------------------------------------
*/
zsi.Util.Common.LoadingBar = function(isVisible) {
    var _ProgressBar = "LoadingProgress";
    var div = $("div." + _ProgressBar)[0];
    var _pageTitleOffset = $($("div.PageTitle")[0]).offset();
    if (isVisible == true) {
        if (div == undefined) {
            var str = "";
            str += "<div class=\"" + _ProgressBar + "\">"
                     + "<div class=\"Icon\" style=\"" + "background-image: url(" + BASE_URL + "images/loading.gif);\"></div>"
                     + "<div class=\"Text\">Proccessing... Pls. wait</div>"
                     + "</div>";
            $(str).appendTo("body");
            div = $("div." + _ProgressBar)[0];
            $(div).dblclick(function() { $(this).fadeOut(); });
        }

        if ($(div).is(":visible") == true) $(div).hide();


        _scrollTop = $(document).scrollTop();
        _scrollLeft = $(document).scrollLeft();
        _top = _pageTitleOffset.top + 22;
        _left = _pageTitleOffset.left;

        if (_scrollTop > _top) _top = _scrollTop;
        if (_scrollLeft > _left) _left = _scrollLeft;

        div.style.top = _top + "px";
        div.style.left = _left + "px";
        $(div).fadeIn();

    }
    else {
        if (div != undefined) {
            $(div).fadeOut();
        }
    }
};


zsi.Util.Common.CheckObjectResponse = function(data, status) {
    var _FunctionName = 'Check Response: ';
    if (status == "success") {
        if (data.ErrMsg) {
            alert(_FunctionName + data.ErrMsg);
            zsi.Util.Common.LoadingBar(false);
            return false;
        }
        else {
            return true;
        }
    }
    else {
        alert(_FunctionName + data);
        zsi.Util.Common.LoadingBar(false);
        return false;
    }
} 

zsi.Util.Common.RequestProblem = function(msg) {
    alert(msg);
    zsi.Util.Common.LoadingBar(false);
}


//----zsi.Util.Common.Form--------------------//
zsi.Util.Common.Form = function() { }

//Form.Fill function
zsi.Util.Common.Form.Fill = function() {
    var args = arguments;
    var info = args[0];
    var Content = args[1];
    var _jObj = $("#" + Content);

    if (args.length == 1) {
        _jObj = $(" :input");
        //fill all input fields  
        _jObj.each(function() {
            var _FieldName = this.name.replace("p_", "");
            var _val = info[_FieldName];
            if (_val) {
                $(this).val(info[_FieldName]);
            }
        });    
    }
    if (args.length == 2) {
        if ($(_jObj[0]).is(" :input")) {
            //fill input fields based from the selected parameters/delimited string
            var _id = Content.split(",");
            for (var i = 0; i < _id.length; i++) {
                var _jqField = $("#" + _id[i]);
                if (_jqField.val) {
                    var _jsonFieldName = _id[i].replace("p_", "");
                    if (_jqField) _jqField.val(info[_jsonFieldName]);
                }
            }
        }
        else {
            var _objContent = $("#" + Content + " :input");
            //fill input fields  based from the object
            _objContent.each(function() {

                var _FieldName = this.name.replace("p_", "");

                var _val = info[_FieldName];
                if (_val) {
                    $(this).val(info[_FieldName]);
                }
            });
        } 
    }
}

//Form.Submit function
zsi.Util.Common.Form.Submit = function () {
    var args = arguments;
    var Action = args[0];           //string URL or Object form
    var Parameters = args[1]        //string Parameters
    var CallBackFunction = args[2]; //function Parameter
    var ResponseType = args[3];     //Data ResponseType or Parameter

    var _action = "";
    var _parameters = "";

    this.BaseFunction = function (data, status) {
        if (zsi.Util.Common.CheckObjectResponse(data, status) == false) return;
        if ((typeof data).toLowerCase() == "string") {
            if(data.trim()=="") return;
            alert("check response:" + data);
            zsi.Util.Common.LoadingBar(false);
            return; 
        }
        var r = JSON.stringify(data
            , function (key, value) {
                if (value == null) {
                    return "";
                }
                else {
                    return value;
                }
            }
        );
        var newData = JSON.parse(r);
        if (newData) CallBackFunction(newData, status);
    }

    if (typeof (Action) == "object") {
        _action = $(Action).attr("action");
        var DisabledObjects = new Array;
        //unlock all disabled objects
        $.each($("[disabled]"), function () {
            DisabledObjects.push(this);
            $(this).attr("disabled", false);
        });
        _parameters = $(Action).serialize();
        //locked objects
        $.each($(DisabledObjects), function () {
            $(this).attr("disabled", true);
        });
        if (_parameters && Parameters) _parameters += "&" + Parameters;
    }

    else {
        _action = Action;
        _parameters = Parameters;
    }

    switch (args.length) {
        case 3: $.post(_action, _parameters, this.BaseFunction); break;
        case 4: $.post(_action, _parameters, this.BaseFunction, ResponseType); break;
        default: break;
    }
};

//Form.Clear function
zsi.Util.Common.Form.ClearFields = function () {
    var args = arguments;
    var Control = args[0];      //Object Id or Form Id, or ID's Parameter
    var _jObj = $("#" + Control);
    var inputs = null;
    if (args.length == 0) {
        //Clear all fields.
        inputs = $(" :input");
        inputs.each(function () {
            $(this).val("");
        });
    }

    if (args.length == 1) {
        if ($(_jObj[0]).is(" :input")) {
            //Clear all fields on a specific list of IDs.
            var _id = Control.split(",");
            for (var i = 0; i < _id.length; i++) {
                var _jqField = $("#" + _id[i]);
                if (_jqField) _jqField.val("");
            }
        }
        else {
            //if (Content) {
            //Clear all fields on a specific content or form.
            inputs = $("#" + Control + " :input");
            inputs.each(function () {
                $(this).val("");
            });
        }
    }
}

zsi.Util.Common.Form.RequiredFields = function (p_NoteId,p_LogicalOperator, p_InputIds) {
    var _result = false;
    var _counter = 0;
    var _strRequired;
    var _arr_inputIdsDesc = null;
    var _arr_inputs = p_InputIds.split(",");
    var _OutputResult = "";
    var _val = "";
    if (arguments[3]) _arr_inputIdsDesc = arguments[3].split(",");
    p_LogicalOperator = p_LogicalOperator.trim().toLowerCase();

    for (var i = 0; i < _arr_inputs.length; i++) {
        var _item = $(_arr_inputs[i]);
        var _itemObj = _item.get(0);
        if (!_itemObj) { alert("id: " + _arr_inputs[i] + " is not defined."); _result = false; break; }
        if (_itemObj.tagName.toLowerCase() == "select") {
            if (_itemObj.options.length == 0) _val = ""; else _val = _item.val();
        }
        else _val = _item.val();

        if (_val == "" || (_itemObj.tagName.toLowerCase() == "select" && _val == "0")) {
            _counter += 1;
            if (_arr_inputIdsDesc)
                _OutputResult = setValue(_OutputResult, _arr_inputIdsDesc[i]);
            else
                _OutputResult = setValue(_OutputResult, _arr_inputs[i]);
        }
    }

    switch (p_LogicalOperator) {
        case "or": if (_counter == _arr_inputs.length) { _OutputResult = "Required either of the following: " + _OutputResult; _result = true; } break;
        case "and": if (_counter <= _arr_inputs.length && _counter != 0) { _OutputResult = "Required input field(s): " + _OutputResult; _result = true; } break;
        default: _result = false; break;
    }
    
    if (_result) {
        var rl = $(p_NoteId);
        if (rl.get(0)) rl.append("<li>" + _OutputResult + "</li>"); else alert(_OutputResult);
    }

    return _result;

    function setValue(p_object, p_value) {
        if (p_value) {
            if (p_object == "") p_object += p_value; else p_object += ", " + p_value;
            return p_object;
        }

    }
}


//----End Of zsi.Util.Common.Form--------------------//
zsi.Util.Common.Window = function() { }
zsi.Util.Common.Window.OpenPopUp = function () {
    var args = arguments;
    var _page = args[0];
    var _properties = args[1];
    var win = null;

    if (args.length == 1) {
        var posX = (screen.width - 700) / 2;
        var posY = (screen.height - 400) / 2;
        win = window.open(_page, '_blank', 'location=no,channelmode=no,directories=no,fullscreen=no,height=400,width=700,menubar=no,status=no,titlebar=no,toolbar=no,scrollbars=yes,left=' + posX + ',top=' + posY);
        win.window.focus();
    }

    if (args.length == 2) {
        win = window.open(_page, '_blank', 'location=no,channelmode=no,directories=no,fullscreen=no,menubar=no,status=no,titlebar=no,toolbar=no,scrollbars=yes,' + _properties);
        win.window.focus();
    }
}

zsi.Util.Common.Window.PopUpModel = function() {
    if (DHTMLSuite == undefined) { alert("DHTML Suite not set"); return; }
    var args = arguments;
    //windowName,WindowTitle,TabTitle, height, width, xPosition, yPosition
    this.WindowModel = new DHTMLSuite.windowModel();
    this.Window = new DHTMLSuite.windowWidget();
    this.__WindowName = args[0]; // windowName;
    this.__WindowTitle = args[1]; //WindowTitle
    this.__TabTitle = args[2];  //TabTitle
    this.__Height = args[3];    //height
    this.__Width = args[4];     //width
    this.__XPosition = args[5]; //xPosition
    this.__YPosition = args[6]; //yPosition
    this.__Init = function() {
        $("#" + this.__WindowName).attr("windowproperties", "title:&nbsp;" + this.__WindowTitle);
        $("#" + this.__WindowName + "Tab").attr("class", "DHTMLSuite_windowContent").attr("tabproperties", "tabTitle:&nbsp;" + this.__TabTitle);
        this.WindowModel.createWindowModelFromMarkUp(this.__WindowName);
        this.WindowModel.resizable = true;
        this.WindowModel.closable = true;
        this.WindowModel.maxWidth = 900;
        this.WindowModel.dragable = true;
        this.WindowModel.xPos = this.__XPosition;
        this.WindowModel.yPos = this.__YPosition;
        this.WindowModel.minHeight = this.__Height;
        this.WindowModel.minWidth = this.__Width;
        this.WindowModel.__setWidth(this.__Width);
        this.WindowModel.__setHeight(this.__Height);
        this.Window.addWindowModel(this.WindowModel);
        this.Window.init();

    }
    this.__Init();
    this.Show = function() {
        this.Window.show();
        this.Window.setHeightOfWindow(this.__Height);
        this.Window.setWidthOfWindow(this.__Width);
    }
    this.Close = function() {

        this.Window.close();
    }
}


//----End Of zsi.Util.Common.Window--------------------//

//----zsi.Util.Common.Cookie--------------------//
zsi.Util.Common.Cookie = function() { }
zsi.Util.Common.Cookie.Read = function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
zsi.Util.Common.Cookie.Create = function (name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

//----End zsi.Util.Common.Cookie--------------------//

zsi.Util.Common.CoverPage = function() {
    var _doc = $(document);
    var _top = _doc.scrollTop();
    var _left = _doc.scrollLeft();

    var _width = _doc[0].body.offsetWidth;
   // var _height = $(document).height();

    var _modalCoverName = "#ModalCover";
    var _m = $(_modalCoverName);
        if (_m[0] == undefined) {
            var _str = "<div id='ModalCover'></div>";
            $(_str).appendTo("body");
            _m = $(_modalCoverName);
        }
    _m.css({
            backgroundColor: '#000'
            , position: 'absolute'
            , top: _top
            , left: _left
            , width: _width
            , height: $(document).height()
            , opacity: 0.50
        });
}


zsi.Util.Common.LoginForm = function() { }
zsi.Util.Common.LoginForm.Init = function() {
    var _width = document.body.offsetWidth;
    var _height = $(document).height();
    var _LoginFormName = "#LoginForm";
    var _l = $(_LoginFormName);
    if (_l[0] == undefined) {
        var _s = "<div id='LoginForm'  style='background-image:url("  + BASE_URL + "images/login-screen.png);'>"
                  /*  + "<p>&nbsp;</p>"
                    + "<p><input type='text' id='p_UserName' name='p_UserName' style='float:left;margin-left:210px;width:135px;margin-top:28px; border-width: 0px;background-color: Transparent;'/> </p>"
                   + "<p><input type='password' id='p_Password' name='p_Password' style='float:left;margin-left:210px;width:135px;margin-top:10px; border-width: 0px;background-color: Transparent;'/> </p>"
                    + "<br />"

                    + "<input type='image' style='float:left;margin-left:205px;margin-top:5px;border-width: 0px;' src='" + BASE_URL + "images/login-button.png' onClick='zsi.Util.Common.LoginForm.OnSignIn();'>"
                    
                    + "<div class='PageContentBottomHeight'></div>"
                    + "</div>" */
        $(_s).appendTo("body");
        _l = $(_LoginFormName);
    }


    _l.css(
        {
            position: 'absolute'
            , top:  230 //(_height / 2) - (171 / 2)
            , left: (_width / 2) - (404 / 2)
            , width: 393 //404
            , height: 163 //171
            , display: 'none'
        });
}

zsi.Util.Common.LoginForm.OnSignIn = function () {
    var _UserName = $("#p_UserName").val();
    if (!_UserName) {
        alert("Enter Username");
        return;
    }
    var _parameters = "p_UserName=" + _UserName + "&p_Password=" + $("#p_Password").val();
    zsi.Util.Common.LoadingBar(true);
    zsi.Util.Common.Form.Submit(BASE_URL + "User/GetUserInfo", _parameters,
    function (data, status) {
        if (zsi.Util.Common.CheckObjectResponse(data, status) == false) return;
        if (data.IsLoginActive == true) {
            $("#p_Password").val("");
            $("#LoginForm").fadeOut();
            $("#ModalCover").fadeOut();

            if ((data.Password == "") || (data.Password == null)) {
                window.location.href = BASE_URL + "Manage/ChangePassword";
            }
            else {
                window.location.href = BASE_URL;
            }
        }
        else {
            alert("Invalid Username / Password.")
        }
        zsi.Util.Common.LoadingBar(false);
    }
    , "json");
}
//----Start zsi.Util.Common.Convert--------------------//
zsi.Util.Common.Convert = function () { }
zsi.Util.Common.Convert.ToBoolean = function (value) {
    var _value = false;
    if (typeof value == "string") {
        switch (value) {
            case "True":
            case "true":
            case "Yes":
            case "yes":
            case "1": _value = true; break;
            default: break;
        }
    } 
    else {
        _value = Boolean(value);
    }
    return _value;
}
//----End zsi.Util.Common.Convert--------------------//

//----Start zsi.Util.Common.Icons--------------------//
zsi.Util.Common.Icons = function() { };
zsi.Util.Common.Icons.Show = function (IsShow) {
    var IconName = "";
    var _isShow = zsi.Util.Common.Convert.ToBoolean(IsShow);

    if (_isShow == true) {
        IconName = "check";
    } else {
        IconName = "delete"
    }

    return "<img src='" + BASE_URL + "images\/icons\/small\/action_" + IconName + ".gif' \/>";
}
//----End zsi.Util.Common.Icons--------------------//

//----Start zsi.Util.Common.NewGuid--------------------//
zsi.Util.Common.NewGuid = function () {
    this.s4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    //return (this.s4() + this.s4() + "-" + this.s4() + "-" + this.s4() + "-" + this.s4() + "-" + this.s4() + this.s4() + this.s4());    
    return (this.s4() + this.s4() + this.s4());    
};

//----Start zsi.Util.Common.CreateListSession--------------------//
zsi.Util.Common.CreateListSession = function (List, Item, SessionName) {
    if (!Item) return;
    if (Item == List[List.length - 1]) {
        var _Url = window.location.href;
        var _SessionId = zsi.Util.Common.NewGuid();
        _Url = _Url.replace(/#.*/, "");
        _Url += "#Session/" + SessionName + "/" + _SessionId;
        window.location.href = _Url;
    }
};



//init Login
zsi.ready(function() {
    var resultCookie = zsi.Util.Common.Cookie.Read("PNPAuthCookie");
    if (!resultCookie) {
        zsi.Util.Common.CoverPage();
        zsi.Util.Common.LoginForm.Init();
        $("#LoginForm").fadeIn();
        $('#LoginForm input').bind('keypress', function(e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if (code == 13) {
                zsi.Util.Common.LoginForm.OnSignIn();
            }
        });
    }
});


//--Added Prototype:NullToEmpty    :gmf 25/10/2010
String.prototype.NullToEmpty = function() {
    var l_result = this.toLowerCase().replace("null", "");
    return l_result;
}



